<template>
  <div class="app-container">
    <el-card class="filter-container">
      <div class="filter-item">
        <el-form :inline="true" :model="queryParams" size="small">
          <el-form-item label="模板名称">
            <el-input v-model="queryParams.name" placeholder="请输入模板名称" clearable />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="queryParams.type" placeholder="请选择公文类型" clearable>
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="list-container">
      <div class="action-container">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增模板</el-button>
      </div>

      <el-table v-loading="loading" :data="templateList" border>
        <el-table-column label="模板名称" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="类型" prop="type" width="100">
          <template slot-scope="scope">
            {{ formatType(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="creatorName" width="100" />
        <el-table-column label="创建时间" prop="createTime" width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-button 
              size="mini" 
              type="text" 
              @click="handleToggleStatus(scope.row)"
            >{{ scope.row.status === 1 ? '禁用' : '启用' }}</el-button>
            <el-button size="mini" type="text" icon="el-icon-document" @click="handleUseTemplate(scope.row)">使用</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.size"
        @pagination="getList"
      />
    </el-card>

    <!-- 查看模板对话框 -->
    <el-dialog title="查看模板" :visible.sync="viewDialogVisible" width="70%">
      <div class="template-view">
        <h3>{{ viewForm.name }}</h3>
        <div class="template-content" v-html="viewForm.content"></div>
      </div>
    </el-dialog>

    <!-- 编辑模板对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="editDialogVisible" width="70%">
      <el-form ref="editForm" :model="editForm" :rules="rules" label-width="100px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="公文类型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择公文类型" style="width: 100%">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <el-input
            type="textarea"
            v-model="editForm.content"
            :rows="15"
            placeholder="请输入模板内容"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTemplateList, getTemplateDetail, createTemplate, updateTemplate, deleteTemplate, toggleTemplateStatus } from '@/api/template'
import Pagination from '@/components/Pagination'

export default {
  name: 'DocumentTemplate',
  components: { Pagination },
  data() {
    return {
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        name: undefined,
        type: undefined
      },
      // 模板列表
      templateList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 类型选项
      typeOptions: [
        { value: 1, label: '通知' },
        { value: 2, label: '请示' },
        { value: 3, label: '报告' },
        { value: 4, label: '决定' },
        { value: 5, label: '其他' }
      ],
      // 查看对话框
      viewDialogVisible: false,
      viewForm: {},
      // 编辑对话框
      editDialogVisible: false,
      dialogTitle: '',
      editForm: {
        id: undefined,
        name: '',
        type: 1,
        content: '',
        status: 1
      },
      // 表单校验规则
      rules: {
        name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择公文类型', trigger: 'change' }],
        content: [{ required: true, message: '请输入模板内容', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取模板列表
    getList() {
      this.loading = true
      getTemplateList(this.queryParams).then(response => {
        this.templateList = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    // 查询按钮
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    // 重置按钮
    resetQuery() {
      this.queryParams = {
        page: 1,
        size: 10,
        name: undefined,
        type: undefined
      }
      this.getList()
    },
    // 格式化时间
    formatDateTime(datetime) {
      if (!datetime) return ''
      const date = new Date(datetime)
      return date.toLocaleString()
    },
    // 格式化类型
    formatType(type) {
      const typeMap = {
        1: '通知',
        2: '请示',
        3: '报告',
        4: '决定',
        5: '其他'
      }
      return typeMap[type] || '未知'
    },
    // 新增按钮
    handleAdd() {
      this.dialogTitle = '新增模板'
      this.editForm = {
        id: undefined,
        name: '',
        type: 1,
        content: '',
        status: 1
      }
      this.editDialogVisible = true
    },
    // 查看按钮
    handleView(row) {
      this.viewForm = row
      this.viewDialogVisible = true
    },
    // 编辑按钮
    handleEdit(row) {
      getTemplateDetail(row.id).then(response => {
        this.editForm = response.data
        this.dialogTitle = '编辑模板'
        this.editDialogVisible = true
      })
    },
    // 删除按钮
    handleDelete(row) {
      this.$confirm('确认删除该模板吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTemplate(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {})
    },
    // 切换状态
    handleToggleStatus(row) {
      const statusText = row.status === 1 ? '禁用' : '启用'
      this.$confirm(`确认${statusText}该模板吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        toggleTemplateStatus(row.id).then(() => {
          this.$message.success(`${statusText}成功`)
          this.getList()
        })
      }).catch(() => {})
    },
    // 使用模板
    handleUseTemplate(row) {
      this.$router.push({
        path: '/document/create',
        query: { templateId: row.id }
      })
    },
    // 提交表单
    submitForm() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          const method = this.editForm.id ? updateTemplate : createTemplate
          method(this.editForm).then(() => {
            this.$message.success('保存成功')
            this.editDialogVisible = false
            this.getList()
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.action-container {
  margin-bottom: 20px;
}
.template-view {
  padding: 20px;
}
.template-view h3 {
  text-align: center;
  margin-bottom: 20px;
}
.template-content {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
  min-height: 300px;
}
</style> 